package com.zzty.zzlp.controller;

import com.alibaba.fastjson.JSONObject;
import com.zzty.zzlp.commom.Uploader;
import com.zzty.zzlp.entity.*;
import com.zzty.zzlp.service.QuestionService;
import com.zzty.zzlp.service.UserService;
import com.zzty.zzlp.service.User_infoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@Controller
@RequestMapping("userinfo")
public class User_infoController {
    @Autowired
    User_infoService uis;
    @Autowired
    UserService us;
    @Autowired
    QuestionService qe;

    @RequestMapping(value = "/getInfo", method = RequestMethod.POST)
    @ResponseBody

    public User_info getInfo(HttpServletRequest request, Model model) {
//        System.out.println("get");
        User u = (User) request.getSession().getAttribute("User");
        Integer id;
        id = u.getId();
        User_info ui = uis.selectByPrimaryKey(id);
        String name = ui.getName();
        String charactern = ui.getCharactern();
        String sex = ui.getSex();
        Integer age = ui.getAge();
        String mail = ui.getMail();
        String phone = ui.getPhone();
        String nativeplace = ui.getNativeplace();
        String city = ui.getCity();
        String educationexp = ui.getEducationexp();
        String profession = ui.getProfession();
        String englishlevel = ui.getEnglishlevel();
        String functions = ui.getFunctions();
        String selfassessment = ui.getSelfassessment();
        if (name == null) name = "";
        if (charactern == null) charactern = "";
        if (sex == null) sex = "";
        if (mail == null) mail = "";
        if (phone == null) phone = "";
        if (nativeplace == null) nativeplace = "";
        if (city == null) city = "";
        if (educationexp == null) educationexp = "";
        if (profession == null) profession = "";
        if (englishlevel == null) englishlevel = "";
        if (functions == null) functions = "";
        if (selfassessment == null) selfassessment = "";
        ui.setName(name);
        ui.setCharactern(charactern);
        ui.setSex(sex);
        ui.setAge(age);
        ui.setMail(mail);
        ui.setPhone(phone);
        ui.setNativeplace(nativeplace);
        ui.setCity(city);
        ui.setEducationexp(educationexp);
        ui.setProfession(profession);
        ui.setEnglishlevel(englishlevel);
        ui.setFunctions(functions);
        ui.setSelfassessment(selfassessment);
        return ui;
    }

    @RequestMapping(value = "/pro", method = RequestMethod.POST)
    @ResponseBody

    public List<Project> pro(HttpServletRequest request, Model model) {
//        System.out.println("get");
        User u = (User) request.getSession().getAttribute("User");
        Integer id;
        id = u.getId();
        List<Project> ui = uis.selproy(id);
//        for( Project p:ui){
//            System.out.println(p.getName());
//        }
        return ui;
    }

    @RequestMapping(value = "/getQe", method = RequestMethod.POST)
    @ResponseBody

    public Map<String, String> getQe(HttpServletRequest request, Model model) {
        User u = (User) request.getSession().getAttribute("User");
        int classid;
        try {
            classid = u.getClazzId();
        } catch (Exception e) {
            classid = 0;
        }
        int num1 = 0;
        int num2 = 5;
        List<SelfExam> s = uis.sel(classid, num1, num2);
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < s.size(); i++) {
            String b[] = s.get(i).getQuestions().split("\\|");
            String msg = "";

            for (String c : b) {
                msg = msg + getQe2(request, model, Integer.parseInt(c)) + "<p>";
            }
            map.put(s.get(i).getDate(), msg);

        }
//        for (String key : map.keySet()) {
//            System.out.println("key= "+ key );
//            System.out.println("and value= " + map.get(key));
//        }
        return map;
    }

    @RequestMapping(value = "/getQe2", method = RequestMethod.POST)
    @ResponseBody

    public String getQe2(HttpServletRequest request, Model model, Integer id) {
        Question qu = uis.getqu(id);
        String msg = qu.getContent();
        return msg;
    }


    @RequestMapping(value = "/getTe", method = RequestMethod.POST)
    @ResponseBody

    public Map<String, String> getTe(HttpServletRequest request, Model model) {
        User u = (User) request.getSession().getAttribute("User");
        int classid;
        try {
            classid = u.getClazzId();
        } catch (Exception e) {
            classid = 0;
        }
        int num1 = 0;
        int num2 = 5;
        List<TeamExam> s = uis.te(classid, num1, num2);
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < s.size(); i++) {
            String b[] = s.get(i).getQuestions().split("\\|");
            String msg = "";
            for (String c : b) {
                msg = msg + getQe2(request, model, Integer.parseInt(c)) + "<p>";
            }
            map.put(s.get(i).getDate(), msg);

        }
//        for (String key : map.keySet()) {
//            System.out.println("key= "+ key );
//            System.out.println("and value= " + map.get(key));
//        }
        return map;
    }

    @RequestMapping(value = "/gai", method = RequestMethod.POST)
    @ResponseBody

    public User_info gai(HttpServletRequest request, Model model) {
        String name = request.getParameter("a1");
        String charactern = request.getParameter("b1");
        String sex = request.getParameter("a2");
        Integer age = Integer.parseInt(request.getParameter("b2"));
        String mail = request.getParameter("a3");
        String phone = request.getParameter("b3");
        String nativeplace = request.getParameter("a4");
        String city = request.getParameter("b4");
        String educationexp = request.getParameter("a5");
        String profession = request.getParameter("b5");
        String englishlevel = request.getParameter("a6");
        String functions = request.getParameter("b6");
        String selfassessment = request.getParameter("a7");
        if (name == null) name = "";
        if (charactern == null) charactern = "";
        if (sex == null) sex = "";
        if (mail == null) mail = "";
        if (phone == null) phone = "";
        if (nativeplace == null) nativeplace = "";
        if (city == null) city = "";
        if (educationexp == null) educationexp = "";
        if (profession == null) profession = "";
        if (englishlevel == null) englishlevel = "";
        if (functions == null) functions = "";
        if (selfassessment == null) selfassessment = "";
        User_info ui = new User_info();
        User u = (User) request.getSession().getAttribute("User");
        Integer id;
        id = u.getId();

        ui.setuser_id(id);
        ui.setName(name);
        ui.setCharactern(charactern);
        ui.setSex(sex);
        ui.setAge(age);
        ui.setPhone(phone);
        ui.setNativeplace(nativeplace);
        ui.setCity(city);
        ui.setMail(mail);
        ui.setEducationexp(educationexp);
        ui.setProfession(profession);
        ui.setEnglishlevel(englishlevel);
        ui.setFunctions(functions);
        ui.setSelfassessment(selfassessment);
//        System.out.println(".............");
//        System.out.println(ui == null);
        uis.updateByPrimaryKeySelective1(ui);
        return ui;
    }

    @RequestMapping(value = "/selectUserById", method = RequestMethod.POST)
    @ResponseBody

    public User selectUserById(HttpServletRequest request, Model model) {
//        System.out.println("get");
        User ui = (User) request.getSession().getAttribute("User");
        Integer id;
        id = ui.getId();

        User u = us.selectUserById(id);

        return u;
    }


    public static void cutCenterImage(String src, String dest, int w, int h) throws IOException {
        Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");
        ImageReader reader = (ImageReader) iterator.next();
        InputStream in = new FileInputStream(src);
        ImageInputStream iis = ImageIO.createImageInputStream(in);
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        int imageIndex = 0;
        Rectangle rect = new Rectangle((reader.getWidth(imageIndex) - w) / 2, (reader.getHeight(imageIndex) - h) / 2, w, h);
        param.setSourceRegion(rect);
        BufferedImage bi = reader.read(0, param);
        ImageIO.write(bi, "jpg", new File(dest));

    }

    /*
     * 图片裁剪二分之一
     */
    public static void cutHalfImage(String src, String dest) throws IOException {
        Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");
        ImageReader reader = (ImageReader) iterator.next();
        InputStream in = new FileInputStream(src);
        ImageInputStream iis = ImageIO.createImageInputStream(in);
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        int imageIndex = 0;
        int width = reader.getWidth(imageIndex) / 2;
        int height = reader.getHeight(imageIndex) / 2;
        Rectangle rect = new Rectangle(width / 2, height / 2, width, height);
        param.setSourceRegion(rect);
        BufferedImage bi = reader.read(0, param);
        ImageIO.write(bi, "jpg", new File(dest));
    }
    /*
     * 图片裁剪通用接口
     */

    public static void cutImage(String src, String dest, int x, int y, int w, int h) throws IOException {
        Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");
        ImageReader reader = (ImageReader) iterator.next();
        InputStream in = new FileInputStream(src);
        ImageInputStream iis = ImageIO.createImageInputStream(in);
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        Rectangle rect = new Rectangle(x, y, w, h);
        param.setSourceRegion(rect);
        BufferedImage bi = reader.read(0, param);
        ImageIO.write(bi, "jpg", new File(dest));

    }

    /*
     * 图片缩放
     */
    public static void zoomImage(String src, String dest, int w, int h) throws Exception {
        double wr = 0, hr = 0;
        File srcFile = new File(src);
        File destFile = new File(dest);
        BufferedImage bufImg = ImageIO.read(srcFile);
        Image Itemp = bufImg.getScaledInstance(w, h, bufImg.SCALE_SMOOTH);
        wr = w * 1.0 / bufImg.getWidth();
        hr = h * 1.0 / bufImg.getHeight();
        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);
        Itemp = ato.filter(bufImg, null);
        try {
            ImageIO.write((BufferedImage) Itemp, dest.substring(dest.lastIndexOf(".") + 1), destFile);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }


    public String upload1(HttpServletRequest request, String Imgpath) {
//获取支持文件上传的Request对象 MultipartHttpServletRequest
        MultipartHttpServletRequest mtpreq = (MultipartHttpServletRequest) request;
//通过 mtpreq 获取文件域中的文件
        MultipartFile file = mtpreq.getFile("file1");

//通过MultipartFile 对象获取文件的原文件名
        String fileName = file.getOriginalFilename();
//生成一个uuid 的文件名
        UUID randomUUID = UUID.randomUUID();
//获取文件的后缀名
        int i = fileName.lastIndexOf(".");
        String uuidName = randomUUID.toString() + fileName.substring(i);
//获取服务器的路径地址（被上传文件的保存地址）
        String realPath = request.getSession().getServletContext().getRealPath("/file");
//将路径转化为文件夹 并 判断文件夹是否存在
        File dir = new File(realPath);
        if (!dir.exists()) {
            dir.mkdir();
        }
//获取一个文件的保存路径

        String path = Imgpath + "/" + uuidName;

// 为文件这服务器中开辟一给新的空间,*没有数据
// File newFile = new File(path);

        try {
            file.transferTo(new File(path));
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        System.err.println("-----服务器的路径地址为：:" + realPath);
//        System.err.println("-----图片名称为：:" + fileName);
//        System.err.println("-----图片新名称为：:" + uuidName);
//        System.err.println("-----图片新路径为：:" + path);
        return path;
    }

    @Value("${path.photo}")
    private String ImgPath;

    @RequestMapping("uplEditImg")
    @ResponseBody
    public JSONObject uplEditImg(HttpServletRequest request) throws Exception {

        User_infoController uic = new User_infoController();
        String path = uic.upload1(request, ImgPath);
        JSONObject jsonObject = new JSONObject();
        // 将图片上传到本地
        jsonObject.put("path", path);
        return jsonObject;
    }


    @RequestMapping("upload")
    @ResponseBody
    public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User_infoController uic = new User_infoController();
        String path = uic.upload1(request, ImgPath);
        String img1 = request.getParameter("file1");
        String[] msg = img1.split(";");


        String[] w1 = msg[0].split(":");
        double w11 = Double.valueOf(w1[1].substring(1, w1[1].length() - 2));
        int w111 = (int) w11;
        String[] h1 = msg[1].split(":");
        double h11 = Double.valueOf(h1[1].substring(1, h1[1].length() - 2));
        int h111 = (int) h11;
        String[] l1 = msg[2].split(":");
        double l11 = Double.valueOf(l1[1].substring(1, l1[1].length() - 2));
        int l111 = (int) l11;
        String[] t1 = msg[3].split(":");
        double t11 = Double.valueOf(t1[1].substring(1, t1[1].length() - 2));
        int t111 = (int) t11;
        String[] w2 = msg[4].split(":");
        double w22 = Double.valueOf(w2[1].substring(1, w2[1].length() - 2));
        int w222 = (int) w22;
        String[] h2 = msg[5].split(":");
        double h22 = Double.valueOf(h2[1].substring(1, h2[1].length() - 2));
        int h222 = (int) h22;
        String[] l2 = msg[6].split(":");
        double l22 = Double.valueOf(l2[1].substring(1, l2[1].length() - 2));
        int l222 = (int) l22;
        String[] t2 = msg[7].split(":");
        double t22 = Double.valueOf(t2[1].substring(1, t2[1].length() - 2));
        int t222 = (int) t22;
//            System.out.println(w111 + "\t" + h111 + "\t" + l111 + "\t" + t111 + "\t" + w222 + "\t" + h222 + "\t" + l222 + "\t" + t222);
        User_infoController.zoomImage(path, path, w111, h111);
//            System.out.println((l222 - l111) + "\t" + (t222 - t111) + "\t" + w222 + "\t" + h222);
        User_infoController.cutImage(path, path, (l222 - l111), (t222 - t111), w222, h222);
        User ui = (User) request.getSession().getAttribute("User");
        Integer id;
        id = ui.getId();

        int mmm = uis.upImg(path, id);
        response.sendRedirect("../html/main.html#!/setting");
    }

    @RequestMapping("logout")
    @ResponseBody
    public void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession(false);
        session.removeAttribute("User");
    }


    @RequestMapping("del/{id}")
    @ResponseBody
    public void del(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") String id) throws Exception {
        uis.del(Integer.parseInt(id));
    }

    @RequestMapping("ins1")
    @ResponseBody
    public void ins1(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User_infoController ufo = new User_infoController();
        String path = ufo.upload1(request, ImgPath);
        User ui = (User) request.getSession().getAttribute("User");
        Integer id;
        id = ui.getId();
        String pro_img = request.getParameter(path);
        String name = request.getParameter("xmm1");
        String pro_show = request.getParameter("xmjs1");
        String content = request.getParameter("xmpj1");
        String de_cycle = request.getParameter("xmrq1");
        String de_tool = request.getParameter("xmgj1");
        String dev_env = request.getParameter("xmhj1");
    }

    @RequestMapping("judgeOldPwd")
    @ResponseBody
    public Boolean judgeOldPwd(HttpServletRequest request, @PathParam("password") String password) {
        User user = (User) request.getSession().getAttribute("User");
        if (user.getPassword().equals(password)) {
            return true;
        } else {
            return false;
        }
    }

    @RequestMapping("changePwd")
    @ResponseBody
    public void changePwd(HttpServletRequest request, @PathParam("password") String password) {
        User user = (User) request.getSession().getAttribute("User");
        user.setPassword(password);
        us.changPwdById(user);
    }

    @RequestMapping("shangci")
    @ResponseBody
    public void shangci(HttpServletRequest req, HttpServletResponse response) throws Exception {
        User u = (User) req.getSession().getAttribute("User");
        int id;
        id = u.getId();
        String title = req.getParameter("title");
        String author = req.getParameter("author");
        String summary = req.getParameter("summary");
        String content = req.getParameter("msg");
        String img = req.getParameter("tu");
        String tt = req.getParameter("tt");
        if (img == null || img == "")
            img = "";
        Article ac = new Article();
        //得到long类型当前时间
        long l = System.currentTimeMillis();
//new日期对象
        Date date1 = new Date(l);
//转换提日期输出格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = dateFormat.format(date1);
        ac.setTitle(title);
        ac.setAuthor(author);
        ac.setSummary(summary);
        ac.setContent(content);
        ac.setUserId(id);
        ac.setTime(date);
        ac.setImgUrl(img);
        ac.setComment(tt);
        int a = uis.insertA1(ac);
    }

    @RequestMapping("edqq")
    @ResponseBody
    public Article edqq(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User ui = (User) request.getSession().getAttribute("User");
        Integer id;
        id = ui.getId();
        Article al = new Article();
        al = uis.Asel(id);
        if (al == null) {
            Article a2 = new Article();
            a2.setId(0);
            return a2;
        } else {
            String edmsg = al.getContent();
            int edid = al.getId();
            return al;
        }
    }

    @RequestMapping("delEd1")
    @ResponseBody
    public void delEd1(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User ui = (User) request.getSession().getAttribute("User");
        Integer uid;
        uid = ui.getId();
        uis.del1(uid);
    }

    public void delEd2(HttpServletRequest request, HttpServletResponse response, int id) throws Exception {
        User ui = (User) request.getSession().getAttribute("User");
        Integer uid;
        uid = ui.getId();
        uis.del2(id);
    }
}
